/**
 * 
 */
package com.mevoy.async.generator;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.ui.velocity.VelocityEngineFactory;

import com.mevoy.async.bean.UserReport;
import com.mevoy.async.generator.exception.ReportGeneratorException;
import com.mevoy.async.generator.exception.ReportGeneratorInitializationError;

/**
 * @author diegoicosta
 * 
 */
public class UserReportVelocityGenerator<UserReportPojoImpl> implements
		UserReportGenerator {

	private Logger logger = Logger.getLogger(this.getClass());
	private VelocityEngineFactory velocityFactory;
	private String userReportTemplateName;
	private VelocityEngine engine;

	/*
	 * METODOS PUBLICOS
	 */


	public void setVelocityFactory(VelocityEngineFactory velocityFactory) {
		this.velocityFactory = velocityFactory;
		try {
			engine = velocityFactory.createVelocityEngine();
		} catch (VelocityException e) {
			logger.error(e);
			throw new ReportGeneratorInitializationError();
		} catch (IOException e) {
			logger.error(e);
			throw new ReportGeneratorInitializationError();
		}
	}

	public void setUserReportTemplateName(String userReportTemplateName) {
		this.userReportTemplateName = userReportTemplateName;
	}

	public void generateReport(UserReport report)
			throws ReportGeneratorException {
		try {
			Template template = engine.getTemplate(userReportTemplateName);
			VelocityContext context = new VelocityContext();
			context.put("userReport", report);

			BufferedWriter writer = new BufferedWriter(new FileWriter("repo-"
					+ report.getReportId() + ".html"));

			template.merge(context, writer);
			writer.close();
		} catch (VelocityException e) {
			logger.error(e);
			throw new ReportGeneratorException();

		} catch (Exception e) {
			logger.error(e);
			throw new ReportGeneratorException();
		}

	}

}
